<template>
  <div class="data-show-container">
    <!-- 用户趋势分析 -->
    <div class="chart-section">
      <div class="chart-header">
        <div class="chart-title">用户趋势分析</div>
        <div class="chart-actions">
          <el-select v-model="timeRange" placeholder="选择时间范围" size="small" :loading="loading">
            <el-option label="最近7天" value="7" />
            <el-option label="最近30天" value="30" />
            <el-option label="最近90天" value="90" />
          </el-select>
        </div>
      </div>
      <div ref="userTrendChart" class="chart-container" v-loading="loading"></div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="overview-card">
            <div class="card-title">总用户数</div>
            <div class="card-value">{{ overviewData.totalUsers.toLocaleString() }}</div>
            <div class="card-trend" :class="overviewData.totalGrowthRate >= 0 ? 'up' : 'down'">
              <i :class="overviewData.totalGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ Math.abs(overviewData.totalGrowthRate) }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="overview-card">
            <div class="card-title">今日新增</div>
            <div class="card-value">{{ overviewData.todayNew.toLocaleString() }}</div>
            <div class="card-trend" :class="overviewData.newUserGrowthRate >= 0 ? 'up' : 'down'">
              <i :class="overviewData.newUserGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ Math.abs(overviewData.newUserGrowthRate) }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="overview-card">
            <div class="card-title">活跃用户</div>
            <div class="card-value">{{ overviewData.activeUsers }}</div>
            <div class="card-trend" :class="overviewData.activeGrowthRate >= 0 ? 'up' : 'down'">
              <i :class="overviewData.activeGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ overviewData.activeGrowthRate }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="overview-card">
            <div class="card-title">平均运动时长</div>
            <div class="card-value">{{ overviewData.avgExerciseTime }}分钟</div>
            <div class="card-trend" :class="overviewData.sportTimeGrowthRate >= 0 ? 'up' : 'down'">
              <i :class="overviewData.sportTimeGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ overviewData.sportTimeGrowthRate }}%</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- BMI分布分析 -->  
    <div class="chart-section">
      <div class="chart-header">
        <div class="chart-title">BMI分布分析</div>
        <div class="chart-actions">
          <el-select v-model="bmiAgeRange" placeholder="选择年龄段" clearable style="width: 150px; margin-left: 10px;">
            <el-option
              v-for="item in ageRanges"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div ref="bmiDistributionChart" class="chart-container"></div>
    </div>

    <!-- 运动达成度分析 -->
    <div class="chart-section">
      <div class="chart-header">
        <div class="chart-title">达成度分析</div>
        <div class="chart-actions">
          <el-select v-model="achievementAgeRange" placeholder="选择年龄段" clearable style="width: 150px; margin-left: 10px;">
            <el-option
              v-for="item in ageRanges"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div ref="achievementChart" class="chart-container"></div>
    </div>

    <!-- 用户行为分析 -->
    <div class="chart-section">
      <div class="chart-header">
        <div class="chart-title">用户登录趋势 (最近7天)</div>
      </div>
      <div ref="userBehaviorChart" class="chart-container"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getUserTrendData, getBasicInformation, getTotalByBMI, getSportGoalData, getUserLoginNumData } from '@/api/dataShow'

export default {
  name: 'DataShow',
  data() {
    return {
      userTrendChart: null,
      achievementChart: null,
      bmiDistributionChart: null,
      userBehaviorChart: null,
      chartInstances: {
        trend: null,
        achievement: null,
        bmi: null,
        behavior: null
      },
      timeRange: '7',
      loading: false,
      overviewData: {
        totalUsers: 0,
        todayNew: 0,
        activeUsers: 0,
        avgExerciseTime: 0,
        activeGrowthRate: 0,
        sportTimeGrowthRate: 0
      },
      bmiAgeRange: '',
      achievementAgeRange: '',
      ageRanges: [
        { label: '10-15岁', value: '10-15' },
        { label: '15-20岁', value: '15-20' },
        { label: '20-25岁', value: '20-25' },
        { label: '25-30岁', value: '25-30' },
        { label: '30-35岁', value: '30-35' },
        { label: '35-40岁', value: '35-40' },
        { label: '40-45岁', value: '40-45' },
        { label: '45-50岁', value: '45-50' },
        { label: '50-55岁', value: '50-55' },
        { label: '55-60岁', value: '55-60' }
      ],
    }
  },
  created() {
    this.initData()
  },
  watch: {
    timeRange(newVal) {
      this.fetchUserTrendData(newVal)
    },
    bmiAgeRange: {
      handler(newVal) {
        if (newVal === '') {
          // 当清除BMI图的选择时，只重新获取BMI数据
          this.getBMIData();
        } else {
          this.updateBMIChart();
        }
      }
    },
    achievementAgeRange: {
      handler(newVal) {
        if (newVal === '') {
          // 当清除达成度图的选择时，只重新获取达成度数据
          this.fetchSportGoalData();
        } else {
          this.updateAchievementChart();
        }
      }
    }
  },
  mounted() {
    this.initCharts()
    this.fetchUserTrendData(this.timeRange)
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    Object.values(this.chartInstances).forEach(instance => {
      instance && instance.dispose()
    })
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    async initData() {
      this.loading = true;
      try {
        await Promise.all([
          this.getBasicData(),
          this.getBMIData(),
          this.fetchSportGoalData(),
          this.fetchUserLoginNum()
        ]);
      } catch (error) {
        console.error("Error during initial data loading:", error);
      } finally {
        this.loading = false;
      }
    },
    // 获取基础信息
    async getBasicData() {
      try {
        const res = await getBasicInformation()
        console.log('基础信息数据：', res)
        if (res.code === 200 && res.data) {
          const { acitve, sprotTime } = res.data
          
          let activeGrowthRateNum = 0;
          if (acitve.yesterday === null || acitve.yesterday === undefined) {
            activeGrowthRateNum = acitve.today > 0 ? 100.0 : 0.0;
          } else {
            if (acitve.yesterday === 0) {
              activeGrowthRateNum = acitve.today > 0 ? 100.0 : 0.0;
            } else {
              activeGrowthRateNum = ((acitve.today - acitve.yesterday) / acitve.yesterday * 100);
            }
          }
          const finalActiveGrowthRate = parseFloat(activeGrowthRateNum.toFixed(1));

          let sportTimeGrowthRateNum = 0;
          if (sprotTime.yesterday === null || sprotTime.yesterday === undefined) {
            sportTimeGrowthRateNum = sprotTime.today > 0 ? 100.0 : 0.0;
          } else {
            if (sprotTime.yesterday === 0) {
              sportTimeGrowthRateNum = sprotTime.today > 0 ? 100.0 : 0.0;
            } else {
              sportTimeGrowthRateNum = ((sprotTime.today - sprotTime.yesterday) / sprotTime.yesterday * 100);
            }
          }
          const finalSportTimeGrowthRate = parseFloat(sportTimeGrowthRateNum.toFixed(1));

          // 修改此处：直接计算总运动分钟数，不再计算平均值
          const totalExerciseTimeInMinutes = Math.round(sprotTime.today * 60);

          this.overviewData = {
            ...this.overviewData,
            activeUsers: acitve.today || 0,
            avgExerciseTime: totalExerciseTimeInMinutes || 0, // 更新为总运动分钟数
            activeGrowthRate: finalActiveGrowthRate,
            sportTimeGrowthRate: finalSportTimeGrowthRate
          }
          
          console.log('更新后的概览数据：', this.overviewData)
        } else {
          // Handle cases where res.data might be null or code is not 200
          console.warn('获取基础信息响应异常或无数据:', res);
          // Optionally set overviewData to defaults or show an error
          this.overviewData = {
            ...this.overviewData,
            activeUsers: 0,
            avgExerciseTime: 0,
            activeGrowthRate: 0,
            sportTimeGrowthRate: 0
          }
        }
      } catch (error) {
        console.error('获取基础信息失败：', error)
        // On error, also reset to defaults
        this.overviewData = {
            ...this.overviewData,
            activeUsers: 0,
            avgExerciseTime: 0,
            activeGrowthRate: 0,
            sportTimeGrowthRate: 0
          }
      }
    },
    // 解析年龄范围字符串为最小和最大年龄
    parseAgeRange(ageRange) {
      if (!ageRange) return { minAge: null, maxAge: null };
      const [minAge, maxAge] = ageRange.split('-').map(Number);
      return { minAge, maxAge };
    },
    // 修改获取BMI数据的方法
    async getBMIData() {
      try {
        const { minAge, maxAge } = this.parseAgeRange(this.bmiAgeRange);
        console.log('BMI查询参数：', { minAge, maxAge });
        const res = await getTotalByBMI({ minAge, maxAge });
        console.log('BMI统计数据：', res);
        if (res.code === 200) {
          const { n_low, v_low, n_mid, v_mid, n_fat, v_fat, n_tfat, v_tfat } = res.data;
          if (this.chartInstances.bmi) {
            const option = {
              animation: true,
              animationDuration: 1000,
              animationEasing: 'cubicInOut',
              animationThreshold: 2000,
              animationDelay: function (idx) {
                return idx * 100;
              },
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                },
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: '#eee',
                borderWidth: 1,
                textStyle: {
                  color: '#666'
                },
                formatter: function(params) {
                  let result = params[0].name + '<br/>'
                  params.forEach(param => {
                    const value = param.value.toLocaleString()
                    const color = param.seriesName === '男性' ? '#5470c6' : '#91cc75'
                    result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
                    result += `${param.seriesName}: ${value}人<br/>`
                  })
                  return result
                }
              },
              legend: {
                data: ['男性', '女性'],
                textStyle: {
                  color: '#666'
                },
                top: 0
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '40px',
                containLabel: true
              },
              xAxis: {
                type: 'category',
                data: ['偏瘦', '正常', '超重', '肥胖'],
                axisLine: {
                  lineStyle: {
                    color: '#eee'
                  }
                },
                axisLabel: {
                  color: '#666',
                  fontSize: 12
                }
              },
              yAxis: {
                type: 'value',
                name: '用户数',
                nameTextStyle: {
                  color: '#666',
                  padding: [0, 0, 0, 40]
                },
                axisLabel: {
                  color: '#666',
                  formatter: function(value) {
                    return value >= 1000 ? (value / 1000).toFixed(1) + 'k' : value
                  }
                },
                splitLine: {
                  lineStyle: {
                    color: '#f0f0f0'
                  }
                }
              },
              series: [
                {
                  name: '男性',
                  type: 'bar',
                  barWidth: '40%',
                  animationDuration: 1000,
                  animationEasing: 'cubicInOut',
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#5470c6' },
                      { offset: 1, color: '#91a7ff' }
                    ]),
                    borderRadius: [4, 4, 0, 0]
                  },
                  emphasis: {
                    itemStyle: {
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#3a4d8f' },
                        { offset: 1, color: '#6a7fc0' }
                      ])
                    }
                  },
                  data: [n_low, n_mid, n_fat, n_tfat]
                },
                {
                  name: '女性',
                  type: 'bar',
                  barWidth: '40%',
                  animationDuration: 1000,
                  animationEasing: 'cubicInOut',
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#91cc75' },
                      { offset: 1, color: '#b7e4a8' }
                    ]),
                    borderRadius: [4, 4, 0, 0]
                  },
                  emphasis: {
                    itemStyle: {
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#6a8f4f' },
                        { offset: 1, color: '#8fb07a' }
                      ])
                    }
                  },
                  data: [v_low, v_mid, v_fat, v_tfat]
                }
              ]
            }
            this.chartInstances.bmi.setOption(option, { notMerge: true });
          }
        }
      } catch (error) {
        console.error('获取BMI统计失败：', error);
      }
    },
    async fetchUserTrendData(days) {
      try {
        const response = await getUserTrendData(days)
        if (response.code === 200) {
          const { count, map } = response.data
          
          // 将日期对象转换为数组并排序
          const dates = Object.keys(map).sort()
          
          // 计算每日新增用户数和累计用户数
          const newUsers = []
          const totalUsers = []
          let total = count  // 起始总数
          
          dates.forEach(date => {
            const dailyNew = map[date]  // 当天新增数
            newUsers.push(dailyNew)     // 记录当天新增
            total += dailyNew           // 累加到总数
            totalUsers.push(total)      // 记录累计总数
          })

          // 计算增长率
          const todayNew = newUsers[newUsers.length - 1]
          const yesterdayNew = newUsers[newUsers.length - 2] || 0
          
          // 修改增长率计算逻辑
          let newUserGrowthRate
          if (yesterdayNew === 0) {
            // 如果昨日新增为0，今日有新增，则显示100%
            newUserGrowthRate = todayNew > 0 ? 100 : 0
          } else {
            newUserGrowthRate = ((todayNew - yesterdayNew) / yesterdayNew * 100).toFixed(1)
          }
          
          const totalGrowthRate = ((total - count) / count * 100).toFixed(1)

          // 更新数据概览卡片
          this.overviewData = {
            ...this.overviewData,
            totalUsers: total,
            todayNew: todayNew,
            totalGrowthRate: totalGrowthRate,
            newUserGrowthRate: newUserGrowthRate
          }
          
          this.updateTrendChart(dates, totalUsers, newUsers)
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取用户趋势数据失败:', error)
        this.$message.error('获取数据失败，请稍后重试')
      }
    },
    updateTrendChart(dates, totalUsers, newUsers) {
      if (this.chartInstances.trend) {
        const option = {
          xAxis: {
            data: dates,
            axisLabel: {
              formatter: function(value) {
                // 格式化日期显示
                const date = new Date(value)
                return `${date.getMonth() + 1}/${date.getDate()}`
              }
            }
          },
          series: [
            {
              name: '用户总量',
              data: totalUsers
            },
            {
              name: '日新增用户',
              data: newUsers
            }
          ]
        }
        this.chartInstances.trend.setOption(option)
      }
    },
    updateAchievementChart() {
      if (this.chartInstances.achievement) {
        const option = {
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            borderColor: '#eee',
            borderWidth: 1,
            textStyle: {
              color: '#666'
            },
            formatter: function(params) {
              return `${params.name}<br/>${params.seriesName}: ${params.value}%`
            }
          },
          legend: {
            orient: 'vertical',
            right: '5%',
            top: 'center',
            textStyle: {
              color: '#666'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          series: [
            {
              name: '步数达成度',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['25%', '50%'],
              avoidLabelOverlap: true,
              itemStyle: {
                borderRadius: 6,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: true,
                position: 'center',
                formatter: '步数达成度\n{value}%',
                fontSize: 14,
                fontWeight: 'bold',
                color: '#666'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 16,
                  fontWeight: 'bold'
                },
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.2)'
                }
              },
              data: [
                { 
                  value: 45, 
                  name: '男-已完成',
                  itemStyle: { color: '#5470c6' }
                },
                { 
                  value: 35, 
                  name: '女-已完成',
                  itemStyle: { color: '#91cc75' }
                },
                { 
                  value: 12, 
                  name: '男-未完成',
                  itemStyle: { color: '#91a7ff' }
                },
                { 
                  value: 8, 
                  name: '女-未完成',
                  itemStyle: { color: '#b7e4a8' }
                }
              ]
            },
            {
              name: '运动时长达成度',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['75%', '50%'],
              avoidLabelOverlap: true,
              itemStyle: {
                borderRadius: 6,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: true,
                position: 'center',
                formatter: '运动时长达成度\n{value}%',
                fontSize: 14,
                fontWeight: 'bold',
                color: '#666'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 16,
                  fontWeight: 'bold'
                },
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.2)'
                }
              },
              data: [
                { 
                  value: 38, 
                  name: '男已完成',
                  itemStyle: { color: '#5470c6' }
                },
                { 
                  value: 42, 
                  name: '女已完成',
                  itemStyle: { color: '#91cc75' }
                },
                { 
                  value: 10, 
                  name: '男未完成',
                  itemStyle: { color: '#91a7ff' }
                },
                { 
                  value: 10, 
                  name: '女未完成',
                  itemStyle: { color: '#b7e4a8' }
                }
              ]
            }
          ]
        }
        this.chartInstances.achievement.setOption(option)
      }
    },
    async fetchSportGoalData() {
      try {
        const { minAge, maxAge } = this.parseAgeRange(this.achievementAgeRange);
        console.log('达成度查询参数：', { minAge, maxAge });
        const res = await getSportGoalData({ minAge, maxAge });
        console.log('运动目标达成度数据：', res);
        if (res.code === 200 && res.data) {
          const { step, sportTime } = res.data;
          const newOption = {
            animation: true,
            animationDuration: 1000,
            animationEasing: 'cubicInOut',
            animationThreshold: 2000,
            title: [
              {
                text: '步数达成度',
                left: '25%',
                textAlign: 'center',
                top: '15%', // Adjusted for legend at the top
                textStyle: { fontSize: 16, fontWeight: 'normal', color: '#495057' }
              },
              {
                text: '运动时长达成度',
                left: '75%',
                textAlign: 'center',
                top: '15%', // Adjusted for legend at the top
                textStyle: { fontSize: 16, fontWeight: 'normal', color: '#495057' }
              }
            ],
            tooltip: {
              formatter: function(params) {
                return `${params.seriesName}<br/>${params.name}: ${params.value} (${params.percent}%)`
              }
            },
            legend: {
              orient: 'horizontal',
              left: 'center',
              top: '3%', // Position legend at the top
              // Explicitly define legend data to ensure correct items and order
              data: ['男已完成', '女已完成', '男未完成', '女未完成'], 
              textStyle: {
                color: '#666'
              },
              itemGap: 20 // Add some gap between legend items
            },
            series: [
              {
                name: '步数达成度',
                type: 'pie',
                radius: ['45%', '65%'],
                center: ['25%', '58%'],
                animationDuration: 1000,
                animationEasing: 'cubicInOut',
                avoidLabelOverlap: false, 
                itemStyle: { 
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: { 
                  show: false, 
                },
                emphasis: {
                  label: { 
                    show: true,
                    formatter: function(params) {
                      // params.name should be the name of the hovered slice
                      // params.percent should be its percentage
                      return params.name + '\n' + params.percent + '%';
                    },
                    fontSize: 16,
                    fontWeight: 'bold',
                    color: '#343a40' 
                  },
                  itemStyle: { 
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.2)'
                  }
                },
                data: [
                  { value: step.n_step,    name: '男已完成',   itemStyle: { color: '#5B8FF9' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } },
                  { value: step.v_step,    name: '女已完成',   itemStyle: { color: '#5AD8A6' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } },
                  { value: step.n_un_step, name: '男未完成', itemStyle: { color: '#BEDAFF' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } },
                  { value: step.v_un_step, name: '女未完成', itemStyle: { color: '#BDEFDB' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } }
                ]
              },
              {
                name: '运动时长达成度',
                type: 'pie',
                radius: ['45%', '65%'],
                center: ['75%', '58%'],
                animationDuration: 1000,
                animationEasing: 'cubicInOut',
                avoidLabelOverlap: false,
                itemStyle: { 
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: { 
                  show: false, 
                },
                emphasis: {
                  label: { 
                    show: true,
                    formatter: function(params) {
                      return params.name + '\n' + params.percent + '%';
                    },
                    fontSize: 16,
                    fontWeight: 'bold',
                    color: '#343a40'
                  },
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.2)'
                  }
                },
                data: [
                  { value: sportTime.n_sport,    name: '男已完成',   itemStyle: { color: '#5B8FF9' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } },
                  { value: sportTime.v_sport,    name: '女已完成',   itemStyle: { color: '#5AD8A6' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } },
                  { value: sportTime.n_un_sport, name: '男未完成', itemStyle: { color: '#BEDAFF' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } },
                  { value: sportTime.v_un_sport, name: '女未完成', itemStyle: { color: '#BDEFDB' }, label: { show: false }, labelLine: { show: false }, emphasis: { label: { show: false }, labelLine: { show: false } } }
                ]
              }
            ]
          }
          if (this.chartInstances.achievement) {
            this.chartInstances.achievement.setOption(newOption, { notMerge: true });
          }
        } else {
          this.$message.error(res.msg || '获取运动目标达成度数据失败');
        }
      } catch (error) {
        console.error('获取运动目标达成度数据失败：', error);
        this.$message.error('获取运动目标达成度数据失败，请稍后重试')
      }
    },
    async fetchUserLoginNum() {
      try {
        const res = await getUserLoginNumData()
        console.log('用户登录趋势数据：', res)
        if (res.code === 200 && res.data) {
          const dates = Object.keys(res.data).sort(); // Sort dates if they are keys
          const loginCounts = dates.map(date => res.data[date]);

          // Format dates for X-axis display if necessary (e.g., MM/DD)
          const formattedDates = dates.map(dateStr => {
            const dateObj = new Date(dateStr);
            return `${dateObj.getMonth() + 1}/${dateObj.getDate()}`;
          });

      if (this.chartInstances.behavior) {
            const option = {
              title: {
                // Remove the main title if the section header is enough
                // text: '最近七天用户登录数',
                // left: 'center'
              },
              tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'line' }
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: {
                type: 'category',
                boundaryGap: false, // For a line chart, often looks better
                data: formattedDates,
                axisLine: { lineStyle: { color: '#ccc' } },
                axisLabel: { color: '#666' }
              },
              yAxis: {
                type: 'value',
                name: '登录用户数',
                axisLine: { show: true, lineStyle: { color: '#ccc' } },
                axisLabel: { color: '#666' },
                splitLine: { lineStyle: { color: '#eee' } }
              },
              series: [{
                name: '登录用户数',
                type: 'line',
                smooth: true,
                itemStyle: { color: '#5B8FF9' }, // Use a theme color
                areaStyle: { // Optional: add area style
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(91, 143, 249, 0.5)' },
                    { offset: 1, color: 'rgba(91, 143, 249, 0.1)' }
                  ])
                },
                data: loginCounts
              }]
            };
            this.chartInstances.behavior.setOption(option, { notMerge: true });
          }
        } else {
          this.$message.error(res.msg || '获取用户登录趋势失败');
        }
      } catch (error) {
        console.error('获取用户登录趋势数据失败：', error)
        this.$message.error('获取用户登录趋势数据失败，请稍后重试')
      }
    },
    initCharts() {
      // 初始化用户趋势图
      if (this.$refs.userTrendChart) {
        this.chartInstances.trend = echarts.init(this.$refs.userTrendChart)
        const trendOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            },
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            borderColor: '#eee',
            borderWidth: 1,
            textStyle: {
              color: '#666'
            },
            extraCssText: 'box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); border-radius: 8px;',
            formatter: function(params) {
              let result = params[0].axisValue + '<br/>'
              params.forEach(param => {
                const value = param.seriesName === '用户总量' 
                  ? param.value.toLocaleString() 
                  : param.value
                const color = param.seriesName === '用户总量' ? '#1890ff' : '#ff4d4f'
                result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
                result += `${param.seriesName}: ${value}<br/>`
              })
              return result
            }
          },
          legend: {
            data: ['用户总量', '日新增用户'],
            textStyle: {
              color: '#666'
            },
            top: 0
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '40px',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: [], // Initial empty data, will be updated
            axisPointer: {
              type: 'shadow'
            },
            axisLine: {
              lineStyle: {
                color: '#eee'
              }
            },
            axisLabel: {
              color: '#666',
              formatter: function(value, index) {
                return value // Will be updated with actual dates
              }
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '用户总量',
              position: 'left',
              axisLabel: {
                formatter: function(value) {
                  return value >= 1000 ? (value / 1000).toFixed(1) + 'k' : value
                },
                color: '#666'
              },
              splitLine: {
                lineStyle: {
                  color: '#f0f0f0'
                }
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#1890ff'
                }
              },
              nameTextStyle: {
                color: '#1890ff',
                padding: [0, 0, 0, 40]
              }
            },
            {
              type: 'value',
              name: '日新增用户',
              position: 'right',
              axisLabel: {
                formatter: '{value}',
                color: '#666'
              },
              splitLine: {
                show: false
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#ff4d4f'
                }
              },
              nameTextStyle: {
                color: '#ff4d4f',
                padding: [0, 40, 0, 0]
              }
            }
          ],
          series: [
            {
              name: '用户总量',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 8,
              sampling: 'average',
              itemStyle: {
                color: '#1890ff'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
                  { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
                ])
              },
              emphasis: {
                focus: 'series',
                itemStyle: {
                  borderWidth: 2,
                  borderColor: '#fff',
                  shadowColor: 'rgba(24, 144, 255, 0.5)',
                  shadowBlur: 10
                }
              },
              data: [] // Initial empty data
            },
            {
              name: '日新增用户',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 8,
              yAxisIndex: 1,
              sampling: 'average',
              itemStyle: {
                color: '#ff4d4f'
              },
              emphasis: {
                focus: 'series',
                itemStyle: {
                  borderWidth: 2,
                  borderColor: '#fff',
                  shadowColor: 'rgba(255, 77, 79, 0.5)',
                  shadowBlur: 10
                }
              },
              data: [] // Initial empty data
            }
          ]
        }
        this.chartInstances.trend.setOption(trendOption)
      }

      // 初始化BMI分布图
      if (this.$refs.bmiDistributionChart) {
        this.chartInstances.bmi = echarts.init(this.$refs.bmiDistributionChart)
        const bmiOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            borderColor: '#eee',
            borderWidth: 1,
            textStyle: {
              color: '#666'
            },
            formatter: function(params) {
              let result = params[0].name + '<br/>'
              params.forEach(param => {
                const value = param.value.toLocaleString()
                const color = param.seriesName === '男性' ? '#5470c6' : '#91cc75'
                result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
                result += `${param.seriesName}: ${value}人<br/>`
              })
              return result
            }
          },
          legend: {
            data: ['男性', '女性'],
            textStyle: {
              color: '#666'
            },
            top: 0
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '40px',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: ['偏瘦', '正常', '超重', '肥胖'],
            axisLine: {
              lineStyle: {
                color: '#eee'
              }
            },
            axisLabel: {
              color: '#666',
              fontSize: 12
            }
          },
          yAxis: {
            type: 'value',
            name: '用户数',
            nameTextStyle: {
              color: '#666',
              padding: [0, 0, 0, 40]
            },
            axisLabel: {
              color: '#666',
              formatter: function(value) {
                return value >= 1000 ? (value / 1000).toFixed(1) + 'k' : value
              }
            },
            splitLine: {
              lineStyle: {
                color: '#f0f0f0'
              }
            }
          },
          series: [
            {
              name: '男性',
              type: 'bar',
              barWidth: '40%',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#5470c6' },
                  { offset: 1, color: '#91a7ff' }
                ]),
                borderRadius: [4, 4, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#3a4d8f' },
                    { offset: 1, color: '#6a7fc0' }
                  ])
                }
              },
              data: [320, 832, 601, 234]
            },
            {
              name: '女性',
              type: 'bar',
              barWidth: '40%',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#91cc75' },
                  { offset: 1, color: '#b7e4a8' }
                ]),
                borderRadius: [4, 4, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#6a8f4f' },
                    { offset: 1, color: '#8fb07a' }
                  ])
                }
              },
              data: [220, 932, 701, 334]
            }
          ]
        }
        this.chartInstances.bmi.setOption(bmiOption)
      }

      // 初始化运动达成度图
      if (this.$refs.achievementChart) {
        this.chartInstances.achievement = echarts.init(this.$refs.achievementChart)
        // 修改为适合饼图的初始配置
        const initialAchievementOption = {
          tooltip: {
            trigger: 'item' 
            // formatter will be set by fetchSportGoalData
          },
          legend: {
            show: true,
            orient: 'horizontal',
            left: 'center',
            top: '3%',
            textStyle: { color: '#666' },
            itemGap: 20
            // data will be set by fetchSportGoalData
          },
          series: [] // Initial series will be empty, fully defined by fetchSportGoalData
        }
        this.chartInstances.achievement.setOption(initialAchievementOption)
      }

      // 初始化用户行为图
      if (this.$refs.userBehaviorChart) {
        this.chartInstances.behavior = echarts.init(this.$refs.userBehaviorChart)
        // Basic line chart configuration
        const initialBehaviorOption = {
          tooltip: {
            trigger: 'axis'
          },
          grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
          xAxis: {
            type: 'category',
            data: [], // Will be populated by fetchUserLoginTrend
            axisLine: { lineStyle: { color: '#ccc' } },
            axisLabel: { color: '#666' }
          },
          yAxis: {
            type: 'value',
            name: '登录用户数',
            axisLine: { show: true, lineStyle: { color: '#ccc' } },
            axisLabel: { color: '#666' },
            splitLine: { lineStyle: { color: '#eee' } }
          },
          series: [] // Will be populated by fetchUserLoginTrend
        }
        this.chartInstances.behavior.setOption(initialBehaviorOption)
      }
    },
    handleResize() {
      Object.values(this.chartInstances).forEach(instance => {
        instance && instance.resize()
      })
    },
    updateBMIChart() {
      // 根据选择的年龄段更新BMI图表数据
      this.getBMIData();
    },
    initBMIChart() {
      // Implementation of initBMIChart method
    },
    updateAchievementChart() {
      // 根据选择的年龄段更新达成度图表数据
      this.fetchSportGoalData();
    },
    initAchievementChart() {
      // Implementation of initAchievementChart method
    },
    resetCharts() {
      // 重新调用获取数据的接口
      this.getBMIData();
      this.fetchSportGoalData();
    },
  }
}
</script>

<style lang="scss" scoped>
.data-show-container {
  padding: 24px;
  background-color: #f6f8fa;
  min-height: calc(100vh - 84px);
  transition: all 0.3s ease;

  .chart-section {
    background: #fff;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
    }

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;

      .chart-title {
        font-size: 18px;
        font-weight: 600;
        color: #1a1a1a;
        position: relative;
        padding-left: 12px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background: #1890ff;
          border-radius: 2px;
        }
      }

      .chart-actions {
        :deep(.el-select),
        :deep(.el-radio-group) {
          .el-input__wrapper {
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
            transition: all 0.3s ease;

            &:hover {
              box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            }
          }
        }

        :deep(.el-radio-button__inner) {
          border-radius: 8px;
          transition: all 0.3s ease;
        }
      }
    }

    .chart-container {
      height: 400px;
      width: 100%;
      transition: all 0.3s ease;
    }
  }

  .overview-cards {
    margin-bottom: 24px;

    .overview-card {
      background: #fff;
      padding: 24px;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      height: 100%;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
      }

      .card-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        gap: 8px;

        &::before {
          content: '';
          display: inline-block;
          width: 6px;
          height: 6px;
          background: #1890ff;
          border-radius: 50%;
        }
      }

      .card-value {
        font-size: 28px;
        font-weight: 600;
        color: #1a1a1a;
        margin-bottom: 12px;
        font-family: 'DIN Alternate', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      }

      .card-trend {
        font-size: 13px;
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 4px 8px;
        border-radius: 6px;
        width: fit-content;

        i {
          font-size: 14px;
        }

        &.up {
          color: #52c41a;
          background: rgba(82, 196, 26, 0.1);
        }

        &.down {
          color: #ff4d4f;
          background: rgba(255, 77, 79, 0.1);
        }
      }
    }
  }
}

// 添加图表加载动画
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

// 优化滚动条样式
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
</style> 